import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/pages/models/auth_application_model.dart';
import 'package:inmotion_pro/pages/models/http_response/apply_owner_response_model.dart';
import 'package:inmotion_pro/pages/models/http_response/http_response_model.dart';
import 'package:inmotion_pro/pages/models/http_response/ride_record_response_model.dart';
import 'package:inmotion_pro/pages/models/http_response/vehicle_info_detail_response_model.dart';
import 'package:inmotion_pro/pages/models/vehicle_model.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../custom_exception/api_exception.dart';
import '../pages/models/user_model.dart';

// 车辆相关的API扩展
extension ApiHelperVehicleExtension on ApiHelper {
  // MARK: - 上传车辆连接信息
  Future<bool> uploadVehicleConnectionInfo(String sn, String connectionInfo) {
    return Future(() => true);
  }

  // MARK: - 检查车辆是否可用
  Future<bool> checkVehicleAvailable(String sn) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v1/product/availability",
      HttpResponseModel.fromJson,
      queryParameters: {
        "sn": sn,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.vehicleAvailable;
    });
  }

  // MARK: - 获取授权车辆列表
  /// [sn] 当传入sn时，只返回该sn对应的车辆信息
  /// [recently] 当传入true时，只返回最近一条车辆连接记录对应的车辆信息
  Future<List<VehicleModel>> getAuthorizedVehicleList({
    String? sn,
    bool? recently,
  }) {
    return httpManager.request<VehicleModel>(
      RequestType.GET,
      "/v2/vehicle/all",
      VehicleModel.fromJson,
      queryParameters: {
        if (sn != null) "sn": sn,
        if (recently != null) "recently": recently,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      List<VehicleModel> vehicleList = response.listData ?? [];
      // 标记为车主
      for (var vehicle in vehicleList) {
        vehicle.isOwner.value = true; // 默认都是车主身份
      }
      return vehicleList;
    });
  }

  // MARK: - 获取最新骑行记录ID
  Future<int> getLatestRideRecordId(String sn) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v1/product/riding-records/latest-id",
      HttpResponseModel.fromJson,
      queryParameters: {
        "sn": sn,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.latestRideRecordId;
    });
  }

  // MARK: - 上传骑行记录
  Future<bool> uploadCyclingRecord(String sn, String records) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/product/riding-records",
      HttpResponseModel.fromJson,
      data: {
        "sn": sn,
        "records": records,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 获取骑行记录列表
  Future<RideRecordResponseModel> getCyclingRecords(
    String sn, {
    int? page,
    int? pageSize,
    int? year,
    int? month,
  }) {
    return httpManager.request<RideRecordResponseModel>(
      RequestType.POST,
      "/v2/product/riding-records",
      RideRecordResponseModel.fromJson,
      data: {
        "sn": sn,
        if (year != null) "year": year,
        if (month != null) "month": month,
        if (page != null) "page": page,
        if (pageSize != null) "page_size": pageSize,
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!;
    });
  }

  // MARK: - 获取车辆信息详情
  Future<VehicleInfoDetailRspModel> getVehicleInfoDetail(String sn) {
    return httpManager.request<VehicleInfoDetailRspModel>(
      RequestType.GET,
      "/v1/product/detail",
      VehicleInfoDetailRspModel.fromJson,
      queryParameters: {
        "sn": sn,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!;
    });
  }

  // MARK: - 获取车辆授权车主列表
  Future<List<UserModel>> getVehicleAuthorizedOwners(String sn) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/owners/list",
      HttpResponseModel.fromJson,
      queryParameters: {
        "sn": sn,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.listData == null) {
        throw ApiException(response.code, response.message);
      }
      return response.listData!
          .map((e) => UserModel.fromMap(e.originData))
          .toList();
    });
  }

  // MARK: - 申请车主
  Future<ApplyOwnerResponseModel> applyOwnerAuth(String sn, String bleName) {
    return httpManager.request<ApplyOwnerResponseModel>(
      RequestType.POST,
      "/v2/owners/apply",
      ApplyOwnerResponseModel.fromJson,
      data: {
        "sn": sn,
        "device_name": bleName,
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!;
    });
  }

  // MARK: - 取消主车主
  Future<bool> cancelCertificationOwner(String sn) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/product/owner/remove",
      HttpResponseModel.fromJson,
      data: {
        "sn": sn,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 取消副车主
  Future<bool> cancelCertificationSecondaryOwner(String sn, {int? userId}) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/product/owner/remove",
      HttpResponseModel.fromJson,
      data: {
        "sn": sn,
        if (userId != null) "vice_owner_user_id": userId,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 获取副车主申请列表
  Future<List<AuthApplicationModel>> getSecondaryOwnerApplicationList(
      {required bool toMe}) {
    return httpManager.request<AuthApplicationModel>(
      RequestType.GET,
      "/v1/product/owner/request/list",
      AuthApplicationModel.fromJson,
      data: {
        "type": toMe ? "to_me" : "from_me",
      },
    ).then((response) {
      if (!response.isSuccess || response.listData == null) {
        throw ApiException(response.code, response.message);
      }
      return response.listData ?? [];
    });
  }

  // MARK: - 处理副车主申请
  Future<bool> handleSecondaryOwnerApplication({
    required int applyId, // 申请id
    required bool accept,
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v1/product/owner/request/process",
      HttpResponseModel.fromJson,
      data: {
        "id": applyId,
        "approved": accept ? 1 : 2, // 1-同意，2-拒绝
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }
}
